package main

import (
	"fmt"
	"net"
	"os"
	"time"
)

//错误处理
func CheckError(err error) {
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

// 模拟网络断开重连
func main() {

	tcpaddr, err := net.ResolveTCPAddr("tcp4", "localhost:7000")
	CheckError(err)
	num := 0

	for {
		conn, err := net.DialTCP("tcp", nil, tcpaddr)

		if err != nil {
			fmt.Println(err)
		} else {
			defer conn.Close()

			if num%2 == 0 {
				sendMsg0(conn)
			} else {
				sendMsg1(conn)
			}
		}
		fmt.Println("main :num=", num)
		time.Sleep(time.Second * 1)
		num++
	}

}

func sendMsg0(conn net.Conn) {
	defer conn.Close()

	num := 0
	for {
		var inputstring string
		fmt.Scanln(&inputstring)
		conn.Write([]byte(inputstring))
		num++
		buf := make([]byte, 1024)
		n, _ := conn.Read(buf)

		fmt.Println(string(buf[:n]))

		if num > 3 {
			return
		}

	}
}

func sendMsg1(conn net.Conn) {
	defer conn.Close()
	num := 0
	for {
		var inputstring string
		fmt.Scanln(&inputstring)
		conn.Write([]byte("我是msg1" + inputstring))

		buf := make([]byte, 1024)
		n, _ := conn.Read(buf)

		fmt.Println(string(buf[:n]))
		num++
		if num > 3 {
			return
		}
	}
}
